<?php
class PayMethod {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 创建支付方式
     */
    public function create(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取用户公司ID
        $companyId = $this->auth->getCompanyId();
        if ($companyId === 0) {
            throw new Exception("用户未绑定公司", 400);
        }

        $data = json_decode(file_get_contents('php://input'), true);

        // 验证必填字段
        if (empty($data['name'])) {
            throw new Exception("支付方式名称不能为空", 400);
        }

        // 插入数据
        $stmt = $this->conn->prepare("
            INSERT INTO paymethods (
                user_id, company_id, name, description, status
            ) VALUES (
                :user_id, :company_id, :name, :description, :status
            )
        ");

        if (!$stmt->execute([
            ':user_id' => $userId,
            ':company_id' => $companyId,
            ':name' => $data['name'],
            ':description' => $data['description'] ?? '',
            ':status' => $data['status'] ?? 1
        ])) {
            throw new Exception("创建支付方式失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '创建成功',
            'data' => ['id' => $this->conn->lastInsertId()]
        ]);
    }

    /**
     * 更新支付方式
     */
    public function update(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取用户公司ID
        $companyId = $this->auth->getCompanyId();
        if ($companyId === 0) {
            throw new Exception("用户未绑定公司", 400);
        }

        $data = json_decode(file_get_contents('php://input'), true);

        if (empty($data['id'])) {
            throw new Exception("缺少支付方式ID", 400);
        }

        // 查询现有支付方式
        $stmt = $this->conn->prepare("
            SELECT * FROM paymethods 
            WHERE id = :id AND company_id = :company_id 
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $data['id'],
            ':company_id' => $companyId
        ]);
        $payMethod = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$payMethod) {
            throw new Exception("支付方式不存在或无权操作", 404);
        }

        // 构建更新字段
        $updateFields = [];
        $params = [':id' => $data['id'], ':company_id' => $companyId];
        
        $allowFields = ['name', 'description', 'status'];
        foreach ($allowFields as $field) {
            if (isset($data[$field])) {
                $updateFields[] = "{$field} = :{$field}";
                $params[":{$field}"] = $data[$field];
            }
        }

        if (empty($updateFields)) {
            throw new Exception("没有可更新的字段", 400);
        }

        // 执行更新
        $sql = "UPDATE paymethods SET " . implode(', ', $updateFields) . " 
                WHERE id = :id AND company_id = :company_id";
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt->execute($params)) {
            throw new Exception("更新支付方式失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '更新成功'
        ]);
    }

    /**
     * 删除支付方式
     */
    public function delete(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取用户公司ID
        $companyId = $this->auth->getCompanyId();
        if ($companyId === 0) {
            throw new Exception("用户未绑定公司", 400);
        }

        $data = json_decode(file_get_contents('php://input'), true);

        if (empty($data['id'])) {
            throw new Exception("缺少支付方式ID", 400);
        }

        // 检查支付方式是否存在且属于当前公司
        $stmt = $this->conn->prepare("
            SELECT id FROM paymethods 
            WHERE id = :id AND company_id = :company_id 
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $data['id'],
            ':company_id' => $companyId
        ]);
        if (!$stmt->fetch()) {
            throw new Exception("支付方式不存在或无权操作", 404);
        }

        // 执行删除
        $stmt = $this->conn->prepare("
            DELETE FROM paymethods 
            WHERE id = :id AND company_id = :company_id
        ");
        if (!$stmt->execute([
            ':id' => $data['id'],
            ':company_id' => $companyId
        ])) {
            throw new Exception("删除支付方式失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '删除成功'
        ]);
    }

    /**
     * 获取支付方式列表
     */
    public function list(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取用户公司ID
        $companyId = $this->auth->getCompanyId();
        if ($companyId === 0) {
            throw new Exception("用户未绑定公司", 400);
        }

        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(100, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = ["company_id = :company_id"];
        $params = [':company_id' => $companyId];

        // 状态筛选
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        // 关键字搜索
        if (!empty($_GET['keyword'])) {
            $where[] = "(name LIKE :keyword OR description LIKE :keyword)";
            $params[':keyword'] = '%' . $_GET['keyword'] . '%';
        }

        $whereClause = implode(' AND ', $where);

        // 查询总数
        $stmt = $this->conn->prepare("
            SELECT COUNT(*) FROM paymethods 
            WHERE {$whereClause}
        ");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();

        // 查询数据
        $stmt = $this->conn->prepare("
            SELECT 
                id, name, description, status,
                create_time, update_time
            FROM paymethods
            WHERE {$whereClause}
            ORDER BY create_time DESC
            LIMIT :offset, :limit
        ");
        
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 获取支付方式详情
     */
    public function detail(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取用户公司ID
        $companyId = $this->auth->getCompanyId();
        if ($companyId === 0) {
            throw new Exception("用户未绑定公司", 400);
        }

        if (empty($_GET['id'])) {
            throw new Exception("缺少支付方式ID", 400);
        }

        $stmt = $this->conn->prepare("
            SELECT 
                id, name, description, status,
                create_time, update_time
            FROM paymethods
            WHERE id = :id AND company_id = :company_id
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $_GET['id'],
            ':company_id' => $companyId
        ]);
        $payMethod = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$payMethod) {
            throw new Exception("支付方式不存在或无权查看", 404);
        }

        echo json_encode([
            'code' => 200,
            'data' => $payMethod
        ]);
    }
}